<template>
  <div class="app-container">
    <el-form ref="formRef" :rules="rules" :model="postForm" class="" label-width="100px">
      <el-form-item label="分类" prop="cate_id" clearable placeholder="请选择">
        <el-cascader
          v-model="postForm.cate_id"
          :options="categoryData"
          :props="{checkStrictly: true, value: 'id', label: 'name'}"
          style="width:100%"
          clearable
          filterable
          placeholder="请选择分类"
          @change="pickCategory"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="postForm.title" clearable placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="封面图" prop="cover_img">
        <el-row :gutter="0">
          <el-col :span="8">
            <el-image v-if="postForm.full_cover_img" :src="postForm.full_cover_img" :preview-src-list="[postForm.full_cover_img]" class="single-image"/>
            <div v-else class="single-image-uploader">
              <div class="el-upload"><i class="el-icon-plus single-image-uploader-icon"></i></div>
            </div>
          </el-col>
          <el-col :span="8">
            <el-button size="mini" @click="fileUpload()">上传图片</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="postForm.desc" type="textarea" clearable placeholder="描述" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div>
          <tinymce-editor v-if="isVisible" v-model="postForm.content" :height="360"/>
        </div>
      </el-form-item>
      <el-form-item label="是否显示" prop="is_show">
        <el-switch v-model="postForm.is_show" :active-value="1" :inactive-value="2"></el-switch>
      </el-form-item>
      <el-form-item label="是否置顶" prop="is_top">
        <el-switch v-model="postForm.is_top" :active-value="1" :inactive-value="2"></el-switch>
      </el-form-item>
      <el-form-item label="是否推荐" prop="is_recommend">
        <el-switch v-model="postForm.is_recommend" :active-value="1" :inactive-value="2"></el-switch>
      </el-form-item>
      <el-form-item label="排序" prop="sorting">
        <el-input-number v-model="postForm.sorting" :min="1" :max="99999" step-strictly controls-position="right"/>
      </el-form-item>
      <el-form-item label="点击数" prop="hits">
        <el-input-number v-model="postForm.hits" :min="1" :max="99999" step-strictly/>
      </el-form-item>
      <el-form-item label="点赞数" prop="likes">
        <el-input-number v-model="postForm.likes" :min="1" :max="99999" step-strictly/>
      </el-form-item>
      <el-form-item v-if="postForm.id" label="创建时间" prop="created_at">
        <el-col :span="10">
          <el-input v-model="postForm.created_at" disabled/>
        </el-col>
        <el-col class="line" :span="4" style="text-align:center">更新时间</el-col>
        <el-col :span="10">
          <el-input v-model="postForm.updated_at" disabled/>
        </el-col>
      </el-form-item>

      <el-form-item label="">
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>

    <!-- 文件管理 -->
    <el-dialog :title="fileTitle" :visible.sync="fileDialog" width="80%" top="10vh" :close-on-click-modal="false">
      <file-manage :file-type="fileType" @fileCancelCallback="fileCancel" @fileSubmitCallback="fileSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import TinymceEditor from '@/components/Tinymce'
import screenHeight from '@/utils/screen-height'
import FileManage from '@/views/admin/iframe/components/File'
import {info, save, cateList as categoryList} from '@/api/admin/article'

const defaultForm = {
  id: '',
  created_at: '',
  updated_at: '',
  title: '',
  cover_img: '',
  full_cover_img: '',
  cate_id: '',
  keywords: '',
  desc: '',
  //content: `<h1 style="text-align: center;">Welcome to the TinyMCE demo!</h1><p style="text-align: center; font-size: 15px;">`,
  content: '',
  is_show: 1,
  is_top: 2,
  is_recommend: 2,
  hits: 1,
  likes: 1,
  sorting: 100,
  status: 1
}

export default {
  name: 'ArticleDetail',
  components: {TinymceEditor, FileManage},
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const nameValidate = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('请至少输入六个字符'))
      } else {
        callback()
      }
    }
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      height: 680,
      isVisible: false,
      loading: false,
      postForm: Object.assign({}, defaultForm),
      btnLoading: false,
      rules: {
        cate_id: [{required: true, message: '请选择分类', trigger: 'blur'}],
        title: [{required: true, trigger: 'change', validator: nameValidate}],
        content: [{validator: validateRequire}],
      },
      categoryData: [],
      tempRoute: {},

      fileDialog: false,
      fileType: 'image',
      fileTitle: '文件管理',

      imgs: [],
      files: [],
      videos: [],

      listLink: '/admin/article'
    }
  },
  created() {
    this.height = screenHeight()

    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.isVisible = true
    }
    this.category()

    // 如果你进入这个页面并快速切换标签，可能是在执行setTagsViewTitle函数时，这个$路由不再指向当前页面
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      info({
        id: id
      }).then(response => {
        this.postForm = response.data
        this.isVisible = true

        // set tagsview title
        this.setTagsViewTitle()
        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    // 取消
    cancel() {
      this.reset()
      this.dialog = false
    },
    // 提交
    submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          this.btnLoading = true
          this.postForm.cate_id = this.getCategory(this.postForm.cate_id)
          save(this.postForm, 'post').then(res => {
            this.btnLoading = false
            this.$message.success(res.msg)
            //this.$router.push(this.listLink)
          }).catch(() => {
            this.btnLoading = false
          })
        }
      })
    },

    setTagsViewTitle() {
      const title = '编辑文章'
      const route = Object.assign({}, this.tempRoute, {title: `${title}-${this.postForm.id}`})
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑文章'
      document.title = `${title} - ${this.postForm.id}`
    },

    // 分类获取
    category() {
      categoryList().then(res => {
        this.categoryData = res.data.data
      }).catch(() => {
      })
    },
    // 选择分类
    pickCategory(value) {
      if (value) {
        //this.postForm.cate_id = this.getCategory(value)
      }
    },
    getCategory(ids) {
      if (Array.isArray(ids)) {
        // 取数组最后一项的值
        return ids[ids.length - 1]
      } else {
        return ids
      }
    },

    // 上传文件
    fileUpload(filetype = 'image', fileTitle = '文件管理') {
      this.fileType = filetype
      this.fileTitle = fileTitle
      this.fileDialog = true
    },
    fileCancel() {
      this.fileDialog = false
    },
    fileSubmit(fileList, fileType) {
      console.log(fileList)
      this.fileDialog = false
      this.fileTitle = ''
      const file_len = fileList.length
      if (fileList) {
        this.postForm.cover_img = fileList[0].file_url
        this.postForm.full_cover_img = fileList[0].full_file_url
        console.log(this.postForm)
        for (let i = 0; i < file_len; i++) {
          if (fileType === 'image') {
            this.imgs.push(fileList[i])
          } else if (fileType === 'word') {
            this.files.push(fileList[i])
          } else if (fileType === 'video') {
            this.videos.push(fileList[i])
          }
        }
      }
    }
  }
}
</script>
